package com.shiwaixiangcun.customer.module.homeservice

import android.content.Context
import android.graphics.Rect
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.google.gson.reflect.TypeToken
import com.jaeger.recyclerviewdivider.RecyclerViewDivider
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterHouseCategory
import com.shiwaixiangcun.customer.adapter.AdapterHouseService
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.BannerBean
import com.shiwaixiangcun.customer.entity.CommonListCallBack
import com.shiwaixiangcun.customer.entity.CommonObjCallBack
import com.shiwaixiangcun.customer.entity.ResponseEntity
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.glide.BannerImageLoader
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.ui.activity.CommonWebActivity
import com.shiwaixiangcun.customer.utils.*
import com.shiwaixiangcun.customer.widget.CustomLoadMoreView
import com.shiwaixiangcun.customer.widget.bannerview.Banner
import kotlinx.android.synthetic.main.activity_home_service_main.*
import kotlinx.android.synthetic.main.top_bar_white.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 到家服务 主页
 */
class HomeServiceMainActivity : BaseActivity(), View.OnClickListener {
    companion object {
        /**
         * 请求数据
         */
        val REQUEST_LIST = 0x0010
        val REQUEST_TYPE = 0x0001
        val REQUEST_BANNER = 0x0011
    }


    /**
     * 点击事件处理
     */
    override fun onClick(p0: View?) {
        val bundle = Bundle()
        when (p0?.id) {
            R.id.back_left -> {

                finish()
            }

        }
    }


    //View
    private var viewBanner: View? = null
    private var viewCategory: View? = null
    private var viewTitle: View? = null

    //widget
    private var mBanner: Banner? = null
    private var mRvCategory: RecyclerView? = null
    private var mDividerView: View? = null

    //List
    private var mHouseList: ArrayList<ServiceData>? = null
    private var mCategoryList: ArrayList<ToHomeServiceType>? = null
    //adapter
    private var mAdapterService: AdapterHouseService? = null
    private var mAdapterCategory: AdapterHouseCategory? = null
    private var strToken: String? = null
    private var refreshToken: String? = null

    //站点Id
    var siteId: Int = 20
    //请求数据 起始页
    private var pageStart: Int = 1
    //每页加载数据size
    var pageSize: Int = 15


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home_service_main)

        EventUtil.getInstance().register(this)
        siteId = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_SITE_ID, 20) as Int
        pageStart = GlobalConfig.first_page
        pageSize = GlobalConfig.page_size
        initHeaderView()
        initViewAndEvent()
        initData(true)
        initBanner()
    }

    /**
     * 获取banner数据
     */
    private fun initBanner() {

        OkGo.get<String>(GlobalApi.getBanner)
                .params("siteId", siteId)
                .params("position", GlobalConfig.SWSH_TOHOMESERVICES_01)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonString = response?.body()
                        val type = object : TypeToken<ResponseEntity<List<BannerBean>>>() {}.type
                        val responseEntity = JsonUtil.fromJson<ResponseEntity<List<BannerBean>>>(jsonString, type)
                        when (responseEntity.responseCode) {
                            1001 -> {
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOME_SERVICE, REQUEST_BANNER, responseEntity.data))

                            }
                        }


                    }
                })

    }

    /**
     * 请求数据
     */
    private fun initData(isRefresh: Boolean) {
        strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        refreshToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_REFRESH_TOKEN, "") as String
        //请求精选服务列表
        OkGo.get<String>(GlobalApi.qualityService)
                .params("page.pn", pageStart)
                .params("page.size", pageSize)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        mAdapterService?.setEnableLoadMore(true)
                        refreshLayout.finishRefresh()
                        mAdapterService?.loadMoreFail()
                    }

                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<CommonObjCallBack<ServiceList>>() {}.type
                        val responseData = JsonUtil.fromJson<CommonObjCallBack<ServiceList>>(response?.body(), type)
                        when (responseData.responseCode) {
                            ResponseConfig.SUCCESS -> {

                                val elements = responseData.data.elements
                                val listSize = if (elements.isEmpty()) 0 else elements.size
                                if (isRefresh) {

                                    refreshLayout.finishRefresh()
                                    mAdapterService?.setEnableLoadMore(true)
                                    if (listSize == 0) {
//                                        cl_nodata.visibility = View.VISIBLE
                                    } else {
                                        mHouseList?.clear()
                                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOME_SERVICE, REQUEST_LIST, responseData.data))
                                    }
                                } else {

                                    if (listSize > 0) {
                                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOME_SERVICE, REQUEST_LIST, responseData.data))
                                    }
                                    if (listSize == 0 || listSize < pageSize) {
                                        mAdapterService?.loadMoreEnd(false)
                                    } else {
                                        mAdapterService?.loadMoreComplete()
                                    }

                                }
                            }

                            ResponseConfig.TOKEN_INVALID -> {
                                showToastShort("当前登录失效")
                                RefreshTokenUtil.refreshToken(mContext, refreshToken)
                            }
                        }

                    }
                })

        //请求服务类型
        OkGo.get<String>(GlobalApi.serviceType)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<CommonListCallBack<ToHomeServiceType>>() {}.type
                        val responseData = JsonUtil.fromJson<CommonListCallBack<ToHomeServiceType>>(response?.body(), type)
                        when (responseData.responseCode) {
                            ResponseConfig.SUCCESS -> {
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOME_SERVICE, REQUEST_TYPE, responseData.data))
                            }
                        }
                    }
                })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.HOME_SERVICE) {
            return
        }
        when (simpleEvent.mEventValue) {
        //获取列表
            REQUEST_LIST -> {
                val serviceList = simpleEvent.data as ServiceList
                //设置精选列表数据
                mHouseList?.addAll(serviceList.elements)
                mAdapterService?.notifyDataSetChanged()


            }


        //获取类型
            REQUEST_TYPE -> {

                val list = simpleEvent.data as List<ToHomeServiceType>

                if (list.isEmpty()) {
                    mRvCategory?.visibility = View.GONE
                    mDividerView?.visibility = View.GONE

                } else {
                    mRvCategory?.visibility = View.VISIBLE
                    mDividerView?.visibility = View.VISIBLE

                    mCategoryList?.clear()
                    mCategoryList?.addAll(list)
                    mAdapterCategory?.notifyDataSetChanged()
                }

            }

        //获取Banner
            REQUEST_BANNER -> {
                val bannerList = simpleEvent.data as List<BannerBean>

                val imageList = bannerList.map { it.imagePath }.toList()

                if (imageList.isEmpty()) {
                    mBanner?.visibility = View.GONE
                } else {
                    mBanner?.visibility = View.VISIBLE
                    mBanner!!.setImages(imageList)
                            .setImageLoader(BannerImageLoader())
                            .setDelayTime(4000)
                            .start()

                    mBanner?.setOnBannerListener { position ->
                        val bannerBean = bannerList[position]
                        when (bannerBean.bannerType) {
                            "H5" -> {
                                val bundle = Bundle()
                                bundle.putString("h5_url", bannerBean.link as String?)
                                bundle.putString("h5_name", "")
                                if (!bannerBean.link.isNullOrEmpty()) {
                                    readyGo(CommonWebActivity::class.java, bundle)
                                }

                            }
                            else -> {
                                UIClickManager.bannerClick(mContext, bannerBean.link)
                            }

                        }
                    }
                }
            }
        }
    }

    /**
     * 初始化试图
     */
    private fun initViewAndEvent() {

        tv_page_name.text = resources.getText(R.string.house_service)
        back_left.setOnClickListener(this)
        mHouseList = ArrayList()
        mAdapterService = AdapterHouseService(mHouseList)


        //设置分类
        mCategoryList = ArrayList()


        mAdapterCategory = AdapterHouseCategory(mCategoryList)


        val gridLayoutManager = GridLayoutManager(mContext, 2)
        mRvCategory?.layoutManager = gridLayoutManager
        mRvCategory?.adapter = mAdapterCategory
        mRvCategory?.addItemDecoration(MarginDecoration(mContext))

        mAdapterCategory?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.data[position] as ToHomeServiceType
            val bundle = Bundle()
            bundle.putLong("type", item.typeId)
            bundle.putString("name", item.serviceTypeName)
            readyGo(CategoryListActivity::class.java, bundle)
        }

        //设置精选List
        mAdapterService?.addHeaderView(viewBanner)
        mAdapterService?.addHeaderView(viewCategory)
        mAdapterService?.addHeaderView(viewTitle)
        rv_home_service.layoutManager = LinearLayoutManager(this)
        rv_home_service.adapter = mAdapterService
        val divider = RecyclerViewDivider.Builder(mContext)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.BETWEEN)
                .setStartSkipCount(1)
                .setEndSkipCount(1)
                .setMarginLeft(20f)
                .setMarginRight(20f)
                .setSize(0.5f)
                .setColorRes(R.color.color_divider_0_1)
                .build()
        rv_home_service.addItemDecoration(divider)
        mAdapterService?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.data[position] as ServiceData
            val bundle = Bundle()
            bundle.putLong("serviceId", item.id)
            readyGo(ServiceDetailActivity::class.java, bundle)
        }


        mAdapterService?.setLoadMoreView(CustomLoadMoreView())
        mAdapterService?.setOnLoadMoreListener({
            pageStart++
            initData(false)
        }, rv_home_service)

        refreshLayout.setOnRefreshListener {
            pageStart = 1
            initData(true)
            mAdapterService?.setEnableLoadMore(false)
        }


    }

    /**
     * 初始化头部
     */
    private fun initHeaderView() {

        viewBanner = layoutInflater.inflate(R.layout.header_banner, null, false)
        viewCategory = layoutInflater.inflate(R.layout.header_service_category, null, false)
        viewTitle = layoutInflater.inflate(R.layout.header_service_title, null, false)

        mRvCategory = viewCategory?.findViewById(R.id.rv_service_category)

        mDividerView = viewTitle?.findViewById(R.id.view_divider)

        mBanner = viewBanner?.findViewById(R.id.banner_header)

        val widthPx = ScreenUtil.getScreenWidth(this)
        val paddingPx = DisplayUtil.dip2px(this, 32f)

        val bannerHeight = (widthPx - paddingPx) / 3
        var layoutParams = mBanner?.layoutParams
        layoutParams?.height = bannerHeight


        mBanner?.layoutParams = layoutParams


    }

    internal inner class MarginDecoration(context: Context) : RecyclerView.ItemDecoration() {
        private val margin: Int = DisplayUtil.dip2px(context, 5f)

        override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
            outRect.set(margin, margin, margin, margin)
        }
    }

    override fun onDestroy() {
        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }
}
